package com.hixtrip.sample.infra;

import com.hixtrip.sample.domain.order.model.Order;
import com.hixtrip.sample.domain.order.repository.OrderRepository;
import com.hixtrip.sample.infra.constant.RedisKeyConstant;
import com.hixtrip.sample.infra.db.convertor.OrderDOConvertor;
import com.hixtrip.sample.infra.db.dataobject.OrderDO;
import com.hixtrip.sample.infra.db.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 订单相关
 */
@Component
public class OrderRepositoryImpl implements OrderRepository {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 新增订单
     */
    @Override
    public Order insert(Order order) {
        OrderDO orderDO = OrderDOConvertor.INSTANCE.domainToDo(order);
        orderMapper.insert(orderDO);
        order.setId(orderDO.getId());
        return order;
    }

    /**
     * 判断是否已支付
     */
    @Override
    public Boolean findIsPay(String orderId) {
        Object data = redisTemplate.boundValueOps(RedisKeyConstant.ORDER_PAY_STATUS + orderId).get();
        return data != null;
    }

    /**
     * 根据 ID 查询订单
     */
    @Override
    public Order getOrderById(String orderId) {
        OrderDO orderDO = orderMapper.selectById(orderId);
        return OrderDOConvertor.INSTANCE.doToDomain(orderDO);
    }

    /**
     * 更新订单数据
     */
    @Override
    public void updateOrder(Order order) {
        OrderDO orderDO = OrderDOConvertor.INSTANCE.domainToDo(order);
        orderMapper.updateById(orderDO);
    }
}
